//店铺数据

var redis=require('./Redis');
var db=require('./db');

function Shop(name){
	this.name=name;
}


//插入数据
Shop.prototype.insert=function(callback){
    var obj={};
    obj["name"]=this.name;
    redis.get("shop.max_id",function(err,reply){
        if(err) return callback(err);
        var id=parseInt(reply)+1;
        var key="shop:"+id;
        obj["id"]=id;
        console.log("插入的数据:"+JSON.stringify(obj));
        redis.set(key,JSON.stringify(obj));
        redis.incr("shop.max_id");
        callback(null);
    })
}

//更新数据
Shop.prototype.update=function(shopId,callback){
    var obj={};
    obj["id"]=shopId;
    obj["name"]=this.name;

    var key="shop:"+shopId;
    redis.set(key,JSON.stringify(obj),function(err,reply){
        console.log("reply:"+reply);
        callback(err);
    });
}


//获取所有的商家数据
Shop.all = function(callback) {
	redis.keys("shop:*",function(err,keys){
		if(err) return callback(err);
        redis.mget(keys,function(error,data){
            return callback(error,data);
        });
    });
}

//根据id查找用户数据
Shop.findById=function(id,callback){
    var key="shop:"+id;
    redis.get(key,function(err,user){
        callback(err,user);
    })
}

//根据id删除数据
Shop.deleteById=function(id,callback){
    var key="shop:"+id;
    redis.del(key,function(err,reply){
        console.log("reply:"+reply);
        callback(err);
    })
}


//同步数据
Shop.syncData=function(){
	db.query("select * from `shop` order by `id` desc",function(err,rows){
		if(err){
			console.error("执行%s语句数据错误,错误详情:"+err,sql);
		}
		else{
			redis.keys("shop:*",function(err,keys){
				if(keys){
					redis.del(keys,function(err,reply){
						for(var i=0;i<rows.length;i++){
							var data=rows[i];
							var key="shop:"+data["id"];
							redis.set(key,JSON.stringify(data));
						}
					})
				}
				else{
					for(var i=0;i<rows.length;i++){
						var data=rows[i];
						var key="shop:"+data["id"];
						redis.set(key,JSON.stringify(data));
					}
				}
			})
		}
		redis.set("shop.max_id",(rows&&rows[0])?rows[0].id:0);
	});
}

//同步Redis数据到数据库
Shop.syncDataToSql=function(){
    Shop.all(function(err,shopes){
        if(err) return console.log("从Redis获取用户数据失败");
        db.query('delete from `shop` where 1=1',function(e,reply){
           if(err) return console.log("清空shop表出错");
           for(var i=0;i<shopes.length;i++){
                var u=JSON.parse(shopes[i]);
                console.log(shopes[i]);
                //插入数据库
                db.query('insert into `shop` (`id`,`name`) values (?,?)',[u.id,u.name]);
            }
        });
        
    })
}



module.exports = Shop;